/**
 * 
 */
var ws=new WebSocket("ws://10.222.29.187:8089/m-version3/ws/push");
	  
(function(){
	var obj={};
	
	obj.ajax=function(type,url,data,headers,context,callback){
		$.ajax({type:type,url:url,data:JSON.stringify(data),headers:headers,context:context})
		.done(callback);
	};
	window.j=obj;
})();


function OrderComponent(template){
	this.model=null;
	
	this.template=template;
	
	this.addNewAddr=function(d){
		j.ajax("POST", 
				"newaddr", 
				d, 
				{"Content-Type":"application/json"}, 
				this, 
				function(dinfolist){
					$("#mymodal").modal("hide");
					this.model=dinfolist;
					addr_select_render(this.model);
		});
	};
	
	this.generateOrder=function(d){
		j.ajax("POST", 
				"addorders", 
				d, 
				{"Content-Type":"application/json"}, 
				this, 
				function(){});
	}
	
	function addr_select_render(data){
		template.empty();
		data.forEach(function(item){
			var contactspan=$("<span></span>").text(item.contact);
			var telspan=$("<span></span>").text(item.tel);
			var addrspan=$("<span></span>").text(item.addr);
			var option=$("<option></option>").attr("name",item.did).text("收件人："+item.contact+"联系电话；"+item.tel+"配送地址："+item.addr);
			option.appendTo(template);
		})
	}
}


$(function(){
	
	var o=new OrderComponent($("#addr-select"));
	$("#newaddr").on("click",function(){
    	//alert("comein..");
        $("#mymodal").modal("show");
    });
	
	$("#save-btn").on("click",function(e){
		var ocontact=$("input[name=contact]","#addrform").val();
		alert(ocontact);
		var otel=$("input[name=tel]","#addrform").val();
		var oaddr=$('#cmbProvince option:selected').html()
				+$('#cmbCity option:selected').html()
				+$('#cmbArea option:selected').html();
		alert(oaddr);
		var o1={"contact":ocontact,"tel":otel,"addr":oaddr};
		alert(o1);
		o.addNewAddr(o1);
	});
	var defaultOption=$("#addr-select option:first").attr("name");
	
	$("#payorder",".right-btn").attr("href","addorders?did="+defaultOption);
	
	
	/*$("select#addr-select").change(function(){
		$("#payorder",".right-btn").attr("href","addorders?did="+did);
	})*/
	
	
  $("#payorder").click(function(e){
	  console.log("a");

	  var icnum=$("#icnum").val();
  	//var icnum="12345678998765432";
	  alert(icnum);
	  ws.send(icnum+"_200");//下订单发送200到M
    
	  //select选择地址
	  var did=$('#addr-select option:selected').attr("name");
	  window.location.href="addorders?did="+did;
    })
    
})
